﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Restbucks
{
    // Define a class to hold custom event info
    public class DebugEventArgs : EventArgs
    {
        public DebugEventArgs(string s)
        {
            message = s;
        }
        private string message;

        public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }

    // Class that publishes an event
    class Debug
    {
        public static Debug Instance = new Debug();
        public static event EventHandler<DebugEventArgs> RaiseLogEvent;

        public static void Log(string stuff)
        {
            Instance.OnRaiseCustomEvent(new DebugEventArgs(stuff));
        }

        public static void Log(Exception e)
        {
            string s = e.ToString();
            Instance.OnRaiseCustomEvent(new DebugEventArgs(s));
        }

        // Wrap event invocations inside a protected virtual method
        // to allow derived classes to override the event invocation behavior
        protected  void OnRaiseCustomEvent(DebugEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<DebugEventArgs> handler = RaiseLogEvent;

            // Event will be null if there are no subscribers
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message = String.Format("{0}: {1}\n", DateTime.Now.ToString(), e.Message);

                // Use the () operator to raise the event.
                handler(this, e);
            }
        }
    }

}
